//
//  ZKWKUserContentController.m
//  StudentKudou
//
//  Created by 赵坪生 on 2017/5/11.
//  Copyright © 2017年 赵坪生. All rights reserved.
//

#import "ZKWKUserContentController.h"

@interface ZKWKUserContentController()
@property (nonatomic, weak)ZKWKWebViewController *viewController;

@end

@implementation ZKWKUserContentController
- (instancetype)initWithViewController:(ZKWKWebViewController *)viewController{
    self = [super init];
    if (self) {
        self.viewController = viewController;
        [self addScriptMessageHandler];
    }
    return self;
}

//注册供JS调用的方法
- (void)addScriptMessageHandler{
    /*  前端需要用 window.webkit.messageHandlers.注册的方法名.postMessage({body:传输的数据} 来给native发送消息
     *  window.webkit.messageHandlers.sayhello.postMessage({body: 'hello world!'});
     */
    [self addScriptMessageHandler:self name:@"sayhello"];
    [self addScriptMessageHandler:self name:@"share"];
    [self addScriptMessageHandler:self name:@"scriptPlay"];
    [self addScriptMessageHandler:self name:@"enrollActivity"];
    [self addScriptMessageHandler:self name:@"gotoTask"];
    [self addScriptMessageHandler:self name:@"gotoReadPunchCard"];
}

#pragma mark - WKScriptMessageHandler JS回调方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    NSLog(@"js调用的方法名字:%@\n传过来的参数body:%@",message.name, message.body);
    SEL s = NSSelectorFromString([message.name stringByAppendingString:@":"]);
    if ([self respondsToSelector:s]) {
        IMP imp = [self methodForSelector:s];
        void (*func)(id, SEL, id) = (void *)imp;
        func(self, s, message.body);
    }
}

-(void)sayhello:(id)data{
    NSLog(@"%@", data);
}



//Removes all associated user scripts
-(void)dealloc{
    [self removeAllUserScripts];
}
@end
